package com.yd.mq.receiver.core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * 
 * @ClassName MQ2FileCommonServiceImpl
 * @author z
 * @date 2017年8月21日 下午3:04:38
 */
@Service
public class Msg2FileUtils {

	/* 并发处理 */
	private ListeningExecutorService	executorService	= MoreExecutors
			.listeningDecorator(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*6));

	/**
	 * 日志处理
	 */
	private Logger log = Logger.getLogger(this.getClass().getName());

	@Value("${ibmmq.file.path}")
	private String rootPath;

	public void writeFileInit(final String msgXml) {
		List<ListenableFuture<?>> listenableFutures = new ArrayList<>();

		// 并发方式保存数据
		listenableFutures.add(executorService.submit(new Runnable() {
			@Override
			public void run() {
				try {
					writeFile(msgXml);
				} catch (IOException e) {
					e.printStackTrace();
					log.error("mq 写入文件异常！");
				}
			}
		}));

	}

	@Async
	public void writeFile(String msgXml) throws IOException {
		String fileName = UUID.randomUUID().toString().replace("-", "");
		fileName = timeFileName() + "_" + fileName + ".xml";

		// 当前文件路径
		String path = rootPath + currtime_path();
		mkdirs(path);
		// 最终文件名
		path = path + fileName;
		log.info("写入文件：" + path);

		File file = new File(path);

		if (!file.exists()) {
			file.createNewFile();
		}
		FileWriter fw = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);

		bw.write(msgXml);
		bw.close();

	}

	/**
	 * 创建文件夹 @return String @throws
	 */
	private String mkdirs(String path) {
		File file = new File(path);
		if ((!file.exists()) && (!file.isDirectory())) {
			file.mkdirs();
		}
		return path;
	}

	/**
	 * 创建文件名前缀 @return String @throws
	 */
	private String timeFileName() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 根基时间创建文件夹 @return String @throws
	 */
	private String currtime_path() {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-HH");
		String date = sd.format(new Date());
		date = date.replace("-", File.separator);
		return date + File.separator;
	}

	public static void main(String[] args) {
		String msgXml = "<?xml version='1.0' encoding='iso-8859-1'?><WholeMsg MsgMark='120' Priority='2' FieldNum='5'><FM_ALARM_MSG><NeName>test</NeName><FP0>4235997236</FP0><FP1>3937860912</FP1><FP2>1924355675</FP2><FP3>4271899482</FP3><C_FP0>494826907</C_FP0><C_FP1>1102783340</C_FP1><C_FP2>2687342666</C_FP2><C_FP3>3264423003</C_FP3><PortNum>64407</PortNum><ChannelNum>111</ChannelNum><ChannelType>2</ChannelType><SyncCType>1</SyncCType><IntId>0</IntId><TimeStamp>1502160715</TimeStamp><TimeStamp_C></TimeStamp_C><ObjectClass>300</ObjectClass><EventTime>2017-08-08 10:51:43</EventTime><VendorSeverity>**</VendorSeverity><OrgSeverity>2</OrgSeverity><RedefineSeverity>2</RedefineSeverity><AlarmText><![CDATA[#S#6187607  **   GDDT6HXDBQZDG                                             PLMN-PLMN/BSC-912724/BCF-113/BTS-114/TRX-8                                  TRX OPERATION DEGRADED                                                      Started    2017-08-08 10:51:43                                              IntId      1452662                  NotifId       55349                     Suppl info 01 00 00 82 00 00                                                User info  Baseband bus major operation error occurred in ESMx System modul Object                              PROCESSING                              #E#]]></AlarmText><VendorType><![CDATA[PROCESSING]]></VendorType><OrgType>1</OrgType><RedefineType>1</RedefineType><TitleId>112649</TitleId><AlarmTitleTxt><![CDATA[TRX OPERATION DEGRADED]]></AlarmTitleTxt><ActiveStatus>1</ActiveStatus><OmcId>4407</OmcId><OmcAlarmId>55349</OmcAlarmId><CorrString><![CDATA[0]]></CorrString><ProbableCause>7607</ProbableCause><RelatedTkgp>0</RelatedTkgp><LocateInfo><![CDATA[#S#6187607  **   GDDT6HXDBQZDG01 00 00 82 00 00]]></LocateInfo><SeverityKeycode>0</SeverityKeycode><TypeKeycode>0</TypeKeycode><ProbableCauseTxt><![CDATA[TRX OPERATION DEGRADED]]></ProbableCauseTxt><AlarmUnit><![CDATA[0]]></AlarmUnit><AlarmContent><![CDATA[0]]></AlarmContent><SubAlarmType></SubAlarmType><AlarmOrigin><![CDATA[0]]></AlarmOrigin><special_field0><![CDATA[TRX-8]]></special_field0><special_field1><![CDATA[]]></special_field1><special_field2><![CDATA[]]></special_field2><special_field3><![CDATA[#S#6187607  **   GDDT6HXDBQZDG01 00 00 82 00 00]]></special_field3><special_field4><![CDATA[]]></special_field4><special_field5><![CDATA[]]></special_field5><special_field6><![CDATA[]]></special_field6><special_field7><![CDATA[]]></special_field7><special_field8><![CDATA[]]></special_field8><special_field9><![CDATA[]]></special_field9><special_field10><![CDATA[]]></special_field10><special_field11><![CDATA[]]></special_field11><special_field12><![CDATA[3]]></special_field12><special_field13><![CDATA[0]]></special_field13><special_field14><![CDATA[]]></special_field14><special_field15><![CDATA[4]]></special_field15><special_field16><![CDATA[诺西]]></special_field16><special_field17><![CDATA[]]></special_field17><special_field18><![CDATA[]]></special_field18><special_field19><![CDATA[]]></special_field19><special_field20><![CDATA[]]></special_field20><special_field21><![CDATA[]]></special_field21><special_field22><![CDATA[]]></special_field22><special_field23><![CDATA[]]></special_field23><ParentIntId><![CDATA[]]></ParentIntId><ParentObjectClass><![CDATA[]]></ParentObjectClass><site_no><![CDATA[0]]></site_no><ne_location><![CDATA[]]></ne_location><SendType>1</SendType><alarm_abnormal_type>70</alarm_abnormal_type><vendor_id>4</vendor_id><vendor_name>诺西</vendor_name><ne_label>GDDT6HXDBQZDG</ne_label><eqp_object_class>201</eqp_object_class><eqp_label></eqp_label><eqp_int_id></eqp_int_id><extra_string1><![CDATA[0]]></extra_string1><object_level><![CDATA[]]></object_level><site_property_unit><![CDATA[]]></site_property_unit><site_info><![CDATA[0]]></site_info><extra_id1><![CDATA[0]]></extra_id1><alarm_act_count></alarm_act_count><MsgSerial>4407_34546778</MsgSerial></FM_ALARM_MSG></WholeMsg>";

		Msg2FileUtils testFile = new Msg2FileUtils();

		try {
			testFile.writeFile(msgXml);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
